﻿using QPlcPlayer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace QPlcPlayer.Services
{
    public partial class DosingScheduleService : QMainService
    {


        public string AddOrUpdateDosingSchedule(DosingSchedule info)
        {
            var res = "保存成功";
            if (info == null)
            {
                res = "实体不能为空";
                return res;
            }
            //对数据进行检查
            if (info.HourFirst < 0 || info.HourFirst >= 24) return "";

            var db = CreateDbContext();

            //新增
            if (string.IsNullOrWhiteSpace(info.ID))
            {
                info.ID = Guid.NewGuid().ToString();
                db.Set<DosingSchedule>().Add(info);
            }
            else //修改数据
            {
                var exist = db.Set<DosingSchedule>().Find(info.ID);
                if (exist != null)
                {
                    exist.HourFirst = info.HourFirst;
                    exist.MinuteFirst = info.MinuteFirst;
                    exist.HourSecond = info.HourSecond;
                    exist.MinuteSecond = info.MinuteSecond;
                    exist.HourThird = info.HourThird;
                    exist.MinuteThird = info.MinuteThird;

                    exist.First_80 = info.First_80;
                    exist.Second_80 = info.Second_80;
                    exist.Third_80 = info.Third_80;

                    exist.First_120 = info.First_120;
                    exist.Second_120 = info.Second_120;
                    exist.Third_120 = info.Third_120;

                    exist.First_160 = info.First_160;
                    exist.Second_160 = info.Second_160;
                    exist.Third_160 = info.Third_160;

                    exist.First_200 = info.First_200;
                    exist.Second_200 = info.Second_200;
                    exist.Third_200 = info.Third_200;

                }
            }

            db.SaveChanges();

            return res;
        }


        public DosingSchedule GetDosingScheduleByCarId(string carId)
        {
            if (string.IsNullOrEmpty(carId)) return new DosingSchedule();
            var db = CreateDbContext();
            var info = db.Set<DosingSchedule>().FirstOrDefault(x => x.CarId == carId);
            return info;
        }

        public List<DosingSchedule> GetDosingScheduleList()
        {
            var db = CreateDbContext();
            var res = db.Set<DosingSchedule>().ToList();
            return res;
        }

        private static string[] Alphabet = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K" };
        private static Dictionary<string, int> OddNumberMap = new Dictionary<string, int>()
            {
                {"01",0 },{"02",1},{ "03",2},{ "04",3}
            };
        private static Dictionary<string, int> EvenNumberMap = new Dictionary<string, int>()
            {
                {"01",4 },{"02",5},{ "03",6},{ "04",7}
            };
        public TodayDosingSchedule GetTodayDosingSchedulePlus()
        {
            var res = new TodayDosingSchedule();
            var db = CreateDbContext();
            var agvcar = db.Set<AgvCar>().FirstOrDefault(x => x.CarNumber == AppRuntime.CarNumber);
            var schedule = db.Set<DosingSchedule>().FirstOrDefault(x => x.CarId == agvcar.ID);
            var pigeoncages = db.Set<PigeonCage>().Where(x=>AppRuntime.Areas.Contains(x.Building)).Select(x => new PigeonCageModel
            {
                ID = x.ID,
                Building = x.Building,
                Arrange = x.Arrange,
                Group = x.Group,
                Number = x.Number,
                BigNumber = x.BreedingPigeonCount
            }).ToList();
            var childs = db.Set<PigeonChild>().Where(x => x.IsGrown == false && x.CreateDate.HasValue).ToList();

            var allpigeoncages = new List<PigeonCageModel>();
            var barcodecages = new List<PigeonCageModel>();
            var tempDic = new Dictionary<string, PigeonCageModel[]>();
            var CodeMapper = new Dictionary<string, (bool IsOdd, string Code, string Number)>();
            var CodeRelationMapper = new Dictionary<string, string>();
            var FeedRateDic = new Dictionary<string, int[]>();

            for (int i = 0; i < pigeoncages.Count; i++)
            {
                if (!AppRuntime.Areas.Contains(pigeoncages[i].Building)) continue;
                allpigeoncages.Add(pigeoncages[i]);
                if (pigeoncages[i].Number == "04") barcodecages.Add(pigeoncages[i]);
                int.TryParse(pigeoncages[i].Arrange, out var arrange);
                var isOdd = arrange % 2 != 0;
                if (arrange % 2 == 0) arrange -= 1;
                var keyval = $"{pigeoncages[i].Building}_{arrange}_{pigeoncages[i].Group}";
                CodeMapper.Add(pigeoncages[i].ID, (isOdd, keyval, pigeoncages[i].Number));
                CodeRelationMapper.Add(pigeoncages[i].ID, keyval);
                if (!tempDic.ContainsKey(keyval)) tempDic.Add(keyval, new PigeonCageModel[8]);
                if (isOdd) tempDic[keyval][OddNumberMap[pigeoncages[i].Number]] = pigeoncages[i];
                else tempDic[keyval][EvenNumberMap[pigeoncages[i].Number]] = pigeoncages[i];
            }
            for (int i = 0; i < childs.Count; i++)
            {
                if (CodeMapper.ContainsKey(childs[i].PigeonHouseId) && childs[i].CreateDate.HasValue)
                {
                    var number = CodeMapper[childs[i].PigeonHouseId].Number;
                    var isodd = CodeMapper[childs[i].PigeonHouseId].IsOdd;
                    var keyval = CodeMapper[childs[i].PigeonHouseId].Code;
                    var Index = 0;
                    if (isodd) Index = OddNumberMap[number];
                    else Index = EvenNumberMap[number];
                    tempDic[keyval][Index].SmallNumber = childs[i].ChildNumber;
                    tempDic[keyval][Index].SmallBirthDay = childs[i].CreateDate.Value;
                }
            }

            foreach(var item in tempDic)
            {
                var array = new int[item.Value.Length];
                for(int i = 0; i < item.Value.Length; i++)
                {
                    var kk = item.Value[i];
                    var timespan = DateTime.Now - kk.SmallBirthDay;
                    var totalDays =timespan.Days;
                    if (kk.SmallBirthDay.Year < 2000) totalDays = 0;
                    var total = kk.BigNumber * AppRuntime.BigPigeon + kk.SmallNumber * AppRuntime.SmallPigeon[totalDays];
                    var okval = 80;
                    if (total <= 80) okval = 80;
                    else if (total <= 120) okval = 120;
                    else if (total <= 160) okval = 160;
                    else if (total <= 200) okval = 200;
                    array[i] = okval;
                }
                FeedRateDic.Add(item.Key, array);

            }

            res.CagesFeeds = FeedRateDic;
            res.CagesRelations = CodeRelationMapper;
            res.FirstTime = DateTime.Parse($"{schedule.HourFirst}:{schedule.MinuteFirst}:00");
            res.SecondTime = DateTime.Parse($"{schedule.HourSecond}:{schedule.MinuteSecond}:00");
            res.ThirdTime = DateTime.Parse($"{schedule.HourThird}:{schedule.MinuteThird}:00");
            return res;
        }

        public TodayDosingSchedule GetTodayDosingSchedule()
        {
            var res = new TodayDosingSchedule();
            var db = CreateDbContext();
            var agvcar = db.Set<AgvCar>().FirstOrDefault(x => x.CarNumber == AppRuntime.CarNumber);
            var schedule = db.Set<DosingSchedule>().FirstOrDefault(x => x.CarId == agvcar.ID);
            var pigeoncages = db.Set<PigeonCage>().OrderBy(x => x.Building).ThenBy(x => x.Arrange).ThenBy(x => x.Group).ThenBy(x => x.Number).ToList();
            var childs = db.Set<PigeonChild>().Where(x => x.IsGrown == false).ToList();
            var dic = new Dictionary<string, DosingScheduleLog>();

            for (int i = 0; i < pigeoncages.Count; i++)
            {
                res.PigeonCages.Add(new PigeonCageModel
                {
                    ID = pigeoncages[i].ID,
                    Building = pigeoncages[i].Building,
                    Arrange = pigeoncages[i].Arrange,
                    Group = pigeoncages[i].Group,
                    Number = pigeoncages[i].Number,
                });
                var bigPigeon = pigeoncages[i].BreedingPigeonCount;
                if (!dic.ContainsKey(pigeoncages[i].ID))
                {
                    var temp = new DosingScheduleLog
                    {
                        CreateTime = DateTime.Now,
                        BigC = bigPigeon,
                        ID = Guid.NewGuid().ToString(),
                        PigeonHouseId = pigeoncages[i].ID,
                        BigPigeon = AppRuntime.BigPigeon,
                    };
                    dic.Add(pigeoncages[i].ID, temp);
                }
                else
                {
                    dic[pigeoncages[i].ID].BigC++;
                }
            }
            for (int i = 0; i < childs.Count; i++)
            {
                var child = childs[i];
                if (dic.ContainsKey(childs[i].PigeonHouseId) && child.CreateDate.HasValue)
                {

                    dic[child.PigeonHouseId].SmallC += child.ChildNumber;
                    var timespan = DateTime.Now - child.CreateDate.Value;
                    var days = timespan.Days;
                    if (days < AppRuntime.SmallPigeon.Count)
                    {
                        dic[child.PigeonHouseId].SmallPigeon = AppRuntime.SmallPigeon[days];
                    }
                }
            }

            foreach (var item in dic)
            {
                int okval = 80;//80,120,160,200
                var total = item.Value.BigPigeon * item.Value.BigC + item.Value.SmallPigeon * item.Value.SmallC;

                if (total <= 80)
                {
                    okval = 80;

                }
                else if (total <= 120)
                {
                    okval = 120;

                }
                else if (total <= 160)
                {
                    okval = 160;

                }
                else if (total <= 200)
                {
                    okval = 200;

                }


                res.OKSchedues.Add(item.Key, okval);
            }

           


            res.FirstTime = DateTime.Parse($"{schedule.HourFirst}:{schedule.MinuteFirst}:00");
            res.SecondTime = DateTime.Parse($"{schedule.HourSecond}:{schedule.MinuteSecond}:00");
            res.ThirdTime = DateTime.Parse($"{schedule.HourThird}:{schedule.MinuteThird}:00");

            return res;
        }

        public TodayDosingSchedule GetTodayDosingScheduleByQ()
        {
            var res=new TodayDosingSchedule();
            var db = CreateDbContext();
            var agvcar = db.Set<AgvCar>().FirstOrDefault(x => x.CarNumber == AppRuntime.CarNumber);
            var schedule = db.Set<DosingSchedule>().FirstOrDefault(x => x.CarId == agvcar.ID);
            var pigeoncages = db.Set<PigeonCage>().Where(x => AppRuntime.Areas.Contains(x.Building)).Select(x => new PigeonCageModel
            {
                ID = x.ID,
                Building = x.Building,
                Arrange = x.Arrange,
                Group = x.Group,
                Number = x.Number,
                BigNumber = x.BreedingPigeonCount
            }).ToDictionary(x=>x.ID);
            var childs = db.Set<PigeonChild>().Where(x => x.IsGrown == false && x.CreateDate.HasValue).ToList();
            childs.ForEach(x =>
            {
                if (pigeoncages.ContainsKey(x.PigeonHouseId))
                {
                    pigeoncages[x.PigeonHouseId].SmallNumber=x.ChildNumber;
                    pigeoncages[x.PigeonHouseId].SmallBirthDay=x.CreateDate.Value;
                }
            });
            Dictionary<string ,int > OKResult= new Dictionary<string ,int>();
            foreach (var item in pigeoncages)
            {
                var key = item.Key;
              
                var childVal = 0m;
                if (item.Value != null && item.Value.SmallBirthDay.Year > 2000)
                {
                   var childDays= (DateTime.Now - item.Value.SmallBirthDay).Days;
                    if(childDays>=0 && childDays < AppRuntime.SmallPigeon.Count)
                    {
                        childVal = item.Value.SmallNumber * AppRuntime.SmallPigeon[childDays];
                    }
                }
                var val=item.Value.BigNumber*AppRuntime.BigPigeon+childVal;
                int okVal = 0;
                if (val <= 80) okVal = 80;
                else if (val <= 120) okVal = 120;
                else if (val <= 160) okVal = 160;
                else if (val <= 200) okVal = 200;
                else okVal = 200;
                OKResult.Add(key, okVal);   
            }



            res.FirstTime = DateTime.Parse($"{schedule.HourFirst}:{schedule.MinuteFirst}:00");
            res.SecondTime = DateTime.Parse($"{schedule.HourSecond}:{schedule.MinuteSecond}:00");
            res.ThirdTime = DateTime.Parse($"{schedule.HourThird}:{schedule.MinuteThird}:00");
            AppRuntime.TodayDosingSchedule.OKSchedues = OKResult;
            return res;
        }

    }
}
